package com.incross.dawin.http;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import android.content.Context;

import com.incross.dawin.DawinConfig;
import com.incross.dawin.util.BKLog;
import com.incross.dawin.util.CommonUtils;

public class BKHttpRequest {
	// error codes
	public static final int REQUEST_TIMEOUT = -100;
	
	
	private static final int HTTP_REQUEST_TIMEOUT = 2000;
	private static final String HTTP_REQUEST_CHARSET = "UTF-8";
	
	// 20131022 user agent로 os구분 못하는 문제가 발생하여 강제로 구분가능한 String 만듦. --null check 추가
	public static final String HTTP_USER_AGENT =  (System.getProperty("http.agent") != null?"[Dawin Library for Android/Linux] " + System.getProperty("http.agent"):"[Dawin Library for Android/Linux]");
	
	public static HttpResponse getResponseForGet(String url, String queryString, Context context) {
		HttpResponse response = null;
		BKLog.e("%%%%%%%%%%%%%%%%%%%%%%%%% User agent!! " + HTTP_USER_AGENT);
		String uid = CommonUtils.getStringPreference(context, DawinConfig.KEY_UID);
		
		// 20131126 저장된 uid가 있는지 여부 확인
		boolean isSavedUidAvailable = ((uid.equals("") || uid == null) ? false : true);
		
		
		try {
			String requestUrl = url;
			if (queryString != null) {
				requestUrl = requestUrl + "&" + queryString;
			}
			
			
			
			BKLog.i("REQUEST URL with saved UID : " + requestUrl);
			
			AbstractHttpClient httpClient = new DefaultHttpClient();
			HttpParams httpParams = new BasicHttpParams();
			HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
			HttpProtocolParams.setUseExpectContinue(httpParams, false);
			// 20131022 user agent에 os구분자 추가한 String으로 세팅함.
			HttpProtocolParams.setUserAgent(httpClient.getParams(), HTTP_USER_AGENT);
			
			HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_REQUEST_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, HTTP_REQUEST_TIMEOUT);

			HttpGet request = new HttpGet(requestUrl);
			request.setParams(httpParams);
			
			response = httpClient.execute(request);
			// 20131125 UID, TS 저장 및 요청시 추가해서 보내도록 수정. Uniq구분을 위해 일단 기능먼저 삽입함.
			if(!isSavedUidAvailable) {
				BKLog.e("############################################################################");
				List<Cookie> cookies = httpClient.getCookieStore().getCookies();
				for(Cookie coo: cookies) {
					String cookieString = coo.getName() + "=" + coo.getValue() + "; path=" + coo.getPath();
					BKLog.i("domain : " + coo.getDomain());
					BKLog.i("cookieString : " + cookieString);
					BKLog.w("------------------------------");
					
					if(coo.getName().equals(DawinConfig.KEY_UID)) {
						CommonUtils.setStringPreference(context, DawinConfig.KEY_UID, coo.getValue());
						BKLog.i("-- UID saved in preference. --");
					}
					
				}
				BKLog.e("############################################################################");
				BKLog.e("cookies : " + cookies.toString());
				BKLog.e("############################################################################");
				
			}
			
		} catch (ClientProtocolException e) {
			BKLog.e("Client protocol exception : " + e.getLocalizedMessage());
		} catch (IOException e) {
			BKLog.e("IO exception : " + e.getLocalizedMessage());
		}
		return response;
	}
	
	@SuppressWarnings("unchecked")
	public static HttpResponse postClient(String url, String queryString) {
		HttpResponse response = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpParams httpParams = new BasicHttpParams();
			HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
			HttpProtocolParams.setUseExpectContinue(httpParams, false);
			// 20131022 user agent에 os구분자 추가한 String으로 세팅함.
			HttpProtocolParams.setUserAgent(httpClient.getParams(), HTTP_USER_AGENT);
						
			HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_REQUEST_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, HTTP_REQUEST_TIMEOUT);

			@SuppressWarnings("rawtypes")
			ArrayList paramList = new ArrayList();
			if ((queryString != null) && (queryString.length() > 0)) {
				String[] values1 = queryString.split("&");
				if ((values1 != null) && (values1.length > 0)) {
					for (int i = 0; i < values1.length; i++) {
						String[] values2 = values1[i].split("=");
						if ((values2 != null) && (values2.length > 1)) {
							paramList.add(new BasicNameValuePair(values2[0], URLDecoder.decode(values2[1], "UTF-8")));
						}
					}
				}
			}

			UrlEncodedFormEntity ent = new UrlEncodedFormEntity(paramList, "UTF-8");

			HttpPost request = new HttpPost(url);
			request.setParams(httpParams);
			request.setEntity(ent);

			response = httpClient.execute(request);
		} catch (Exception localException) {
		}
		return response;
	}

	@SuppressWarnings("unchecked")
	public static HttpResponse postClient(String token, String ureferer,
			String url, String queryString) {
		HttpResponse response = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpParams httpParams = new BasicHttpParams();
			HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
			HttpProtocolParams.setUseExpectContinue(httpParams, false);
			// 20131022 user agent에 os구분자 추가한 String으로 세팅함.
			HttpProtocolParams.setUserAgent(httpClient.getParams(), HTTP_USER_AGENT);
			
			HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_REQUEST_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, HTTP_REQUEST_TIMEOUT);

			@SuppressWarnings("rawtypes")
			ArrayList paramList = new ArrayList();
			if ((queryString != null) && (queryString.length() > 0)) {
				String[] values1 = queryString.split("&");
				if ((values1 != null) && (values1.length > 0)) {
					for (int i = 0; i < values1.length; i++) {
						String[] values2 = values1[i].split("=");
						if ((values2 != null) && (values2.length > 1)) {
							paramList.add(new BasicNameValuePair(values2[0],
									URLDecoder.decode(values2[1], "UTF-8")));
						}
					}
				}
			}

			UrlEncodedFormEntity ent = new UrlEncodedFormEntity(paramList,
					"UTF-8");

			HttpPost request = new HttpPost(url);
			request.setParams(httpParams);
			request.setHeader("ureferer", ureferer);
			request.setHeader("uinfo", token);
			request.setEntity(ent);

			response = httpClient.execute(request);
		} catch (Exception localException) {
		}
		return response;
	}

	public static HttpResponse deleteClient(String url, String queryString) {
		HttpResponse response = null;
		try {
			String requestUrl = url;
			if (queryString != null) {
				requestUrl = requestUrl + "?" + queryString;
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpParams httpParams = new BasicHttpParams();
			HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
			HttpProtocolParams.setUseExpectContinue(httpParams, false);
			// 20131022 user agent에 os구분자 추가한 String으로 세팅함.
			HttpProtocolParams.setUserAgent(httpClient.getParams(), HTTP_USER_AGENT);
			
			HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_REQUEST_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, HTTP_REQUEST_TIMEOUT);

			HttpDelete request = new HttpDelete(requestUrl);
			request.setParams(httpParams);

			response = httpClient.execute(request);
		} catch (Exception localException) {
		}
		return response;
	}

	public static HttpResponse deleteClient(String token, String ureferer,
			String url, String queryString) {
		HttpResponse response = null;
		try {
			String requestUrl = url;
			if (queryString != null) {
				requestUrl = requestUrl + "?" + queryString;
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpParams httpParams = new BasicHttpParams();
			HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
			HttpProtocolParams.setUseExpectContinue(httpParams, false);
			// 20131022 user agent에 os구분자 추가한 String으로 세팅함.
			HttpProtocolParams.setUserAgent(httpClient.getParams(), HTTP_USER_AGENT);
			
			HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_REQUEST_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, HTTP_REQUEST_TIMEOUT);

			HttpDelete request = new HttpDelete(requestUrl);
			request.setParams(httpParams);
			request.setHeader("ureferer", ureferer);
			request.setHeader("uinfo", token);

			response = httpClient.execute(request);
		} catch (Exception localException) {
		}
		return response;
	}

	public static HttpResponse putClient(String url, String queryString) {
		HttpResponse response = null;
		try {
			String requestUrl = url;
			if (queryString != null) {
				requestUrl = requestUrl + "?" + queryString;
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpParams httpParams = new BasicHttpParams();
			HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
			HttpProtocolParams.setUseExpectContinue(httpParams, false);
			// 20131022 user agent에 os구분자 추가한 String으로 세팅함.
			HttpProtocolParams.setUserAgent(httpClient.getParams(), HTTP_USER_AGENT);
			
			HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_REQUEST_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, HTTP_REQUEST_TIMEOUT);

			HttpPut request = new HttpPut(requestUrl);
			request.setParams(httpParams);

			response = httpClient.execute(request);
		} catch (Exception localException) {
		}
		return response;
	}

}
